package com.weblog.weblog.admin.service.impl;

import com.weblog.weblog.admin.model.vo.user.FindUserInfoRspVO;
import com.weblog.weblog.admin.model.vo.user.UpdateAdminUserPasswordReqVO;
import com.weblog.weblog.admin.service.AdminUserService;
import com.weblog.weblog.common.domain.mapper.UserMapper;
import com.weblog.weblog.common.enums.ResponseCodeEnum;
import com.weblog.weblog.common.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author gc
 * @class_name AdminUserServiceImpl
 * @date 2023年09月19日 18:56
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UserMapper userMapper;

    //密码加密器
    @Autowired
    private PasswordEncoder passwordEncoder;



    /*
     * 修改密码
     * @author gc
     * @date 2023/9/19 19:06
     * @param updateAdminUserPasswordReqVO
     * @return com.weblog.weblog.common.utils.Response
     */

    @Override
    public Response updatePassword(UpdateAdminUserPasswordReqVO updateAdminUserPasswordReqVO) {
        String username = updateAdminUserPasswordReqVO.getUsername();
        String password = updateAdminUserPasswordReqVO.getPassword();

        //加密
        String encode = passwordEncoder.encode(password);

        int i = userMapper.updatePasswordByUsername(username, encode);
        return i == 1 ? Response.success() : Response.fail(ResponseCodeEnum.USERNAME_OR_PWD_ERROR);
    }

    @Override
    public Response findUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String username = authentication.getName();
        return Response.success(FindUserInfoRspVO.builder().username(username).build());
    }
}
